#! /usr/bin/env bash

BUILDIFIER_SHORT_PATH=@@BUILDIFIER_SHORT_PATH@@
ARGS=@@ARGS@@
WORKSPACE="@@WORKSPACE@@"

# Get the absolute path to the buildifier executable
buildifier_short_path=$(readlink "$BUILDIFIER_SHORT_PATH")

# Use TEST_WORKSPACE to determine if the script is being ran under a test
if [[ ! -z "${TEST_WORKSPACE+x}" && -z "${BUILD_WORKSPACE_DIRECTORY+x}" ]]; then
  FIND_FILE_TYPE="l"
  # If WORKSPACE was provided, then the script is being run under a test in no_sandbox mode
  if [[ ! -z "${WORKSPACE:+x}" ]]; then
    FIND_FILE_TYPE="f"

    # resolve the WORKSPACE symlink
    # use `realpath` if available and `readlink` otherwise (typically macOS)
    if command -v realpath &> /dev/null; then
        WORKSPACE_LINK="$(realpath ${WORKSPACE})"
    elif command -v readlink &> /dev/null; then
        WORKSPACE_LINK="$(readlink ${WORKSPACE})"
    else
        echo "Unable to resolve symlink (WORKSPACE: ${WORKSPACE})"
        exit 1
    fi

    # Find the directory containing the WORKSPACE file
    WORKSPACE_PATH="$(dirname "$WORKSPACE_LINK")"

    # Change the working directory to the WORKSPACE parent
    if ! cd "$WORKSPACE_PATH" ; then
      echo "Unable to change to workspace (WORKSPACE_PATH: ${WORKSPACE_PATH})"
    fi
  fi
else
  # Change into the workspace directory if this is _not_ a test
  if ! cd "$BUILD_WORKSPACE_DIRECTORY"; then
    echo "Unable to change to workspace (BUILD_WORKSPACE_DIRECTORY: ${BUILD_WORKSPACE_DIRECTORY})"
    exit 1
  fi
fi

# Run buildifier on all starlark files
find . \
  -type "${FIND_FILE_TYPE:-f}" \
  @@EXCLUDE_PATTERNS@@ \
  \( -name '*.bzl' \
    -o -name '*.sky' \
    -o -name BUILD.bazel \
    -o -name BUILD \
    -o -name '*.BUILD' \
    -o -name 'BUILD.*.bazel' \
    -o -name 'BUILD.*.oss' \
    -o -name MODULE.bazel \
    -o -name WORKSPACE \
    -o -name WORKSPACE.bazel \
    -o -name WORKSPACE.oss \
    -o -name WORKSPACE.bzlmod \
    -o -name 'WORKSPACE.*.bazel' \
    -o -name 'WORKSPACE.*.oss' \
  \) -print | xargs "$buildifier_short_path" "${ARGS[@]}"
